<template>
  <div>
    <h3>用户列表</h3>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="#/welcome">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 简单卡片 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input placeholder="请输入内容">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" @click="centerDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 展示用户列表 -->
      <el-table :data="tableData" stripe border style="width: 100%;margin-top:10px;">
        <el-table-column type="index" width="50">
        </el-table-column>
        <el-table-column prop="username" label="姓名">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column label="状态">
          <!-- slot-scope="scope" 为传入插槽的数据。其中scope.row表示当前行的数据 -->
          <template slot-scope="scope">
            <el-switch @change="userStateChanged(scope.row)" v-model="scope.row.mg_state" active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :enterable="false" content="编辑" placement="top">
              <el-button type="primary" size="mini" icon="el-icon-edit"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :enterable="false" content="删除" placement="top">
              <el-button type="danger" size="mini" icon="el-icon-delete"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :enterable="false" content="分配角色" placement="top">
              <el-button type="warning" size="mini" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[100, 200, 300, 400]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>

      <!-- 添加用户-对话框 -->
      <el-dialog title="添加用户" :visible.sync="centerDialogVisible" width="50%" center>
        <!-- 主体内容 -->
        <el-form ref="addUserForm" :rules="addUserFormRules" :model="addUserForm" label-width="80px" size="small">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>

        </el-form>
        <!-- 操作按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserFormClear">取 消</el-button>
          <el-button type="primary" @click="addUserFormClearYes">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  export default {
    data() {
      // 自定义验证规则
      var validateEmail = (rule, value, callback) => {
        if (!value) {
          // return callback(new Error('邮箱不能为空'));
          return callback()
        } else if (!/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(value)) {
          return callback(new Error('请输入正确的邮箱号'));
        } else {
          return callback()
        }
      }
      var validateMobile = (rule, value, callback) => {
        if (!value) {
          // return callback(new Error('手机号不能为空'));
          return callback()
        } else if (!/^1[3|4|5|8][0-9]\d{4,8}$/.test(value)) {
          return callback(new Error('请输入正确的手机号'));
        } else {
          return callback()
        }
      }
      return {
        // 查询用户列表
        queryInfo: {
          query: "",
          pagenum: 1,
          pagesize: 2,
        },
        //   用户列表的数据
        userList: [],
        //   用户列表总数
        total: 0,
        //   添加用户
        addUserInfo: {
          username: "wwj",
          password: "wwj",
          email: "",
          mobile: "",
        },
        // 用户添加的对话框
        centerDialogVisible: false,
        //   静态数据--用户列表
        tableData: [{
          id: 25,
          username: "tige117",
          mobile: "18616358651",
          type: 1,
          email: "tige112@163.com",
          create_time: "2017-11-09T20:36:26.000Z",
          mg_state: true, // 当前用户的状态
          role_name: "炒鸡管理员",
        }, {
          id: 26,
          username: "tige118",
          mobile: "18616358652",
          type: 1,
          email: "tige112@164.com",
          create_time: "2017-11-09T20:36:26.000Z",
          mg_state: false, // 当前用户的状态
          role_name: "炒鸡管理员",
        }],
        // 发送请求添加新用户
        addUserForm: {
          username: "",
          password: "",
          email: "",
          mobile: ""
        },
        addUserFormRules: {
          username: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }, {
            min: 3,
            max: 5,
            message: '长度在 3 到 5 个字符',
            trigger: 'blur'
          }],
          password: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }],
          email: [{
            validator: validateEmail,
            trigger: "blur"
          }],
          mobile: [{
            validator: validateMobile,
            trigger: "blur"
          }]
        }
      };
    },
    created() {
      this.getUserList();
    },
    methods: {
      // 查询用户列表--后端执行不成功，不知道什么原因，提示 pagenum 参数错误
      async getUserList() {
        var {
          data: res
        } = await this.$http.get("/users", this.queryInfo);
        console.log("用户列表", res);
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg);
        } else {
          this.userList = res.data.users;
          this.total = res.data.totalpage;
        }
      },
      // 监听 pagesize 改变的事件
      handleSizeChange(newSizze) {
        console.log('newSizze---', newSizze)
      },
      // 监听 页码值 改变的事件
      handleCurrentChange(newPage) {
        console.log('newSizze---', newPage)
      },
      // 修改用户状态
      async userStateChanged(userIfon) {
        console.log('userIfon', userIfon)
        // 后端代码执行错误，会直接终止后端服务，所以不用改请求了  
        // const {
        //   data: res
        // } = await this.$http.put(
        //   `users/${userIfon.id}/state/${userIfon.mg_state}`)
        // console.log('修改用户状态', res)
        // if (res.meta.status !== 200) {
        //   userIfon.mg_state = !userIfon.mg_state
        // }
        // return this.$message.error(res.meta.msg);
        return this.$message.error('管理员ID不存在');
      },
      // 添加用户 -- 对话框的取消按钮
      addUserFormClear() {
        this.$refs.addUserForm.resetFields();
        this.centerDialogVisible = false
      },
      // 添加用户 -- 对话框的确认按钮
      addUserFormClearYes() {
        this.$refs.addUserForm.validate(value => {
          if (!value) return;
          // 发送请求---添加新用户---略
          // 静态数据
          this.tableData.push(this.addUserForm)
          this.centerDialogVisible = false
          this.$refs.addUserForm.resetFields();
        })
      }
    },
  };
  //
</script>

<style scoped>
  .el-pagination {
    margin-top: 10px;
  }

  .table-clu-center {
    text-align: center;
  }

  .box-card {
    width: 100%;
    margin-top: 10px;
    box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.15);
  }
</style>